#!/usr/bin/python 
#Name:Yuan Li
#AndrewID:yuanli1


######## Pre-made functions ##########

import random

deck = range(52)

def resetDeck():
    global deck
    deck = range(52)
    
def drawCard():
    global deck
    cardNumber = deck.pop(random.randint(0,len(deck)) - 1)
    suit = cardNumber/13
    face = cardNumber%13
    return "CDHS"[suit] + "A234567890JQK"[face]

######### Student-made functions ##########

def isPair(card1,card2):
	# format checking 
	if (cardFormatCheck(card1) == -1):
		return False

	if (cardFormatCheck(card2) == -1):
		return False

	if card1[1] == card2[1]:
		return True
	else:
		return False


def cardFormatCheck(card):

	# check the length of the card
	if len(card) != 2:
		return -1

	# initial some stuff for checking suit and face
	suit = "CDHS"
	face = "A234567890JQK"
	mark = False

	# checking suit
	for x in suit:
		if card[0] == x:
			mark = True
			break

	# if card is out of 4 suit, then it is invalid	
	if mark == False:
		return -1

	# clear mark
	mark = False

	# checking face
	for x in face:
		if card[1] == x:
			mark = True
			break
	
	# if card is out of 13 value, then it is invalid
	if mark == False:
		return -1

	# if you reach here, it seems everything is OK
	return 0


def pairInHand(hand):
	for select in range(len(hand)):
		for paired in range(select+1,len(hand)):
			if isPair(hand[select],hand[paired]) == True:
				return True

	return False
   

def runTrial():
	cards = 0
	inHand = []	
	resetDeck()

	while cards < 5:
		#resetDeck()
		inHand.append(drawCard())
		cards += 1;
	

	if pairInHand(inHand) == True:
		return True
	else:
		return False


def monteCarlo(trials):
	# input checking 
	if trials <= 0:
		return -1

	suc = 0;
	time = 0;

	while time < trials:
		if runTrial() == True:
			suc += 1
		
		time += 1

	return float(suc)/float(trials)

########## test functions ###########

def testIsPair():
    print "Testing isPair...",
    assert(isPair("HA", "SA") == True)
    assert(isPair("C2", "S0") == False)
    assert(isPair("DA", "DK") == False)
    assert(isPair("G", "Kesden") == False)
    assert(isPair("DH", "CH") == False)
    print "all tests passed!"
    print "(but you should still add some more)!"

def testPairsInHand():
    print "Testing pairsInHand...",
    assert(pairInHand(["DK", "CK"]) == True)
    assert(pairInHand(["H2", "H3", "H4"]) == False)
    assert(pairInHand(["C0","HA","H8","D5","SA"]) == True)
    assert(pairInHand(["Alex", "Carrie", "Phil", "Rich"]) == False)
    print "all tests passed!"
    print "(but you should still add some more)!"


def testMonteCarlo():
    print "Testing imonteCarlo...",
    lowerBound = 0.47
    upperBound = 0.53
    chance = monteCarlo(10 * 1000)
    print "monteCarlo returned", chance, "...",
    assert(chance > lowerBound and chance < upperBound)
    print "all tests passed!"
 

 ################### main routine ####################

testIsPair()
testPairsInHand()
testMonteCarlo()
